<!--
 * @Description: 
 * @version: 
 * @Author: hui.wang01
 * @Date: 2020-12-17 14:21:02
 * @LastEditors: hui.wang01
-->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>防抖&节流</title>
</head>
<body>
  <div id="main"></div>
</body>
<style>
  #main {
    width: 400px;
    height: 400px;
    background-color: bisque;
    font-size:80px;
    color: #000000;
  }
</style>
<script>
  var num = 1;
    var content = document.getElementById('main');

    function count() {
        content.innerHTML = num++;
    };

    content.onmousemove = count;
    content.onmousemove = debounce(count,1000,true);

  //防抖：非立即执行&立即执行结合版本
  function debounce(callback,wait,immediate){
    let timeout = null 
    return function(){
      let context = this 
      let args = arguments 
      if(timeout){
        clearTimeout(timeout)
      }
      if(immediate){
        let callNow = !timeout 
        timeout = setTimeout(()=>{
          timeout = null
        },wait)
        if(callNow){
          callback.apply(context,arguments)
        }
      } else {
        timeout = setTimeout(()=>{
          callback.apply(context,arguments)
        },wait)
      }
    }
  }
</script>
</html>